<template>
  <div
    v-if="moduleNameOptions&&activePageForm&&activePageForm.activeModuleIndex!=null"
    v-loading="loading"
    class="marketing-main"
  >
    <el-form
      v-if="form.type"
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-suffix="："
      size="small"
    >
      <el-form-item>
        <el-tag type="warning">自动获取数据按添加时间倒序排列, 手动添加可自定义顺序排列</el-tag>
      </el-form-item>
      <el-form-item label="数据源" prop="biz.params.activitySource">
        <el-select v-model="form.biz.params.activitySource" placeholder="请选择" clearable class="w-400">
          <el-option :value="1" label="自动从营销中心获取已配置的活动" />
          <el-option :value="0" label="手动添加" />
        </el-select>
        <el-button v-if="form.biz.params.activitySource===0" type="text" @click="openDialogMarketing">&nbsp;添加活动
        </el-button>
      </el-form-item>

      <el-form-item label="类别标题" prop="biz.params.enableActivityTypeTitle">
        <el-select v-model="form.biz.params.enableActivityTypeTitle" placeholder="请选择" class="w-400">
          <el-option :value="true" label="显示" />
          <el-option :value="false" label="隐藏" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.biz.params.activitySource===0" label="" prop="biz.params.activityList">
        <div>
          <ul>
            <draggable
              :list="form.biz.params.activityList"
              :options="{ filter: '.undrag' }"
              @change="moduleDragChange"
            >
              <li
                v-for="(item, index) in form.biz.params.activityList"
                :key="index"
                class="li-container"
              >
                <el-card class="box-card">
                  <div slot="header" class="clearfix">
                    <div class="flexRBC">
                      <div>
                        <span style="fontWeight: bold; line-height: 32px"> {{ index + 1 }}.&nbsp;&nbsp;{{ item.theme
                        }}</span>
                        <el-tag v-if="item.status===1" size="mini" type="success">启用中</el-tag>
                        <el-tag v-if="item.status===2" size="mini" type="danger">已暂停</el-tag>
                        <el-tag v-if="item.status===3" size="mini" type="info">已终止</el-tag>
                      </div>
                      <div>
                        <el-button size="mini" round type="danger" @click="del( index)">删除</el-button>
                        <el-button size="mini" round>拖拽排序</el-button>
                      </div>
                    </div>
                  </div>
                  <div class="flexRBC">
                    <div v-if="item.image" class="pic-box">
                      <el-image :src="fileBaseUrl + item.image" fit="contain" />
                    </div>
                    <div class="content-box">
                      <div>
                        <div class="flexRSS cell-item">
                          <div class="label">活动类型：</div>
                          <div class="value">
                            {{ item.onlyMemberDay ? '会员日' : '' }}{{ $store.state.setting.marketingActivityTypeKeyOptions[item.activityType]||'-' }}
                          </div>
                        </div>
                        <div class="flexRSS cell-item">
                          <div class="label">活动日期：</div>
                          <div class="value">{{ item.startTime + ' ~ ' + item.endTime }}</div>
                        </div>
                      </div>
                    </div>

                  </div>
                </el-card>
              </li>
            </draggable>
          </ul>
        </div>

      </el-form-item>
      <el-form-item>
        <el-button type="primary" round @click="submit">保存</el-button>
        <el-button round @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <DialogMarketing ref="dialogMarketing" />
  </div>
</template>

<script>
import DialogMarketing from './DialogMarketing'
import draggable from 'vuedraggable'
import wxaBuildConfig from '@/views/wxaBuildModule/config'
import { mapGetters } from 'vuex'
import { imgUploadUrl } from '@/api/upload'
import { getActivityListByIds } from '@/api/marketing'

export default {
  components: {
    DialogMarketing,
    draggable
  },
  data() {
    return {
      // 配置
      // 校验字段相关
      rules: {
        'biz.params.activityList': [
          {
            type: 'array',
            required: true,
            message: '请至少选择一种活动',
            trigger: ['blur', 'change']
          }
        ]
      },
      moduleNameOptions: null,
      imageUploadUrl: imgUploadUrl,
      // 状态
      loading: false,
      // 数据
      classifyCode: 'DEFAULT',
      cardList: [],
      form: {
        bg: '',
        biz: {
          params: {
            activitySource: 1,
            enableActivityTypeTitle: false,
            activityList: [],
            activityIds: []
          },
          type: 'MARKETING'
        },
        color: '',
        content: '',
        dump: {
          appId: '',
          feature: '',
          featureParams: '',
          insidePage: '',
          insideParams: '',
          path: '',
          type: 'EMPTY',
          url: ''
        },
        modules: [],
        pic: '',
        ranking: 0,
        style: '',
        subTitle: '',
        subType: '',
        title: '',
        type: 'yingxiaohuodong'
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl', 'activePageForm'])
  },
  watch: {
    'activePageForm.activeModuleIndex'() {
      this.fetchData()
    }
  },
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {
    this.moduleNameOptions = wxaBuildConfig[this.classifyCode].moduleName
    this.fetchData()
  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
  },
  deactivated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  methods: {
    /**
     * 数据组
     */
    // 获取数据
    async fetchData() {
      if (this.activePageForm.modules[this.activePageForm.activeModuleIndex].modules.length) {
        this.mode = 'edit'
        const params = JSON.parse(JSON.stringify(this.activePageForm.modules[this.activePageForm.activeModuleIndex].modules[0]))
        if (params.biz.params.activityIds.length) {
          params.biz.params.activitySource = 0
          params.biz.params.activityList = await this.fetchActivityList(params.biz.params.activityIds) || []
        } else {
          params.biz.params.activitySource = 1
          params.biz.params.activityList = []
        }
        console.log(params)
        this.form = params
      } else {
        this.mode = 'add'
        const params = JSON.parse(JSON.stringify(this.form))
        delete params.biz.params.activitySource
        delete params.biz.params.activityList
        this.activePageForm.modules[this.activePageForm.activeModuleIndex].modules = [params]
      }
    },

    // 获取活动
    fetchActivityList(activityIds) {
      return new Promise((resolve, reject) => {
        this.loading = true
        getActivityListByIds(activityIds).then(res => {
          const params = res.data || []
          params.sort((a, b) => activityIds.findIndex(v => v === a.id) - activityIds.findIndex(v => v === b.id))
          resolve(params)
        }).finally(() => {
          this.loading = false
        })
      })
    },

    /**
     * 按钮组
     */
    // 保存
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.form))
          if (params.biz.params.activitySource === 1) {
            params.biz.params.activityIds = []
          } else {
            params.biz.params.activityIds = []
            params.biz.params.activityList.forEach(v => {
              params.biz.params.activityIds.push(v.id)
            })
          }
          delete params.biz.params.activitySource
          delete params.biz.params.activityList
          this.activePageForm.modules[
            this.activePageForm.activeModuleIndex
          ].modules = [params]
          this.$notify({
            title: '成功',
            message: '已保存模块数据',
            type: 'success',
            duration: 2000,
            offset: 40
          })
        }
      })
    },

    // 重置
    reset() {
      this.$refs.form.resetFields()
    },

    // 删除
    del(index) {
      this.form.biz.params.activityList.splice(index, 1)
      this.$forceUpdate()
    },

    // 拖拽
    moduleDragChange() {
      this.$forceUpdate()
    },

    openDialogMarketing() {
      const hasCheckedIds = []
      this.form.biz.params.activityList
        .forEach((v) => {
          hasCheckedIds.push(v.id)
        })
      this.$refs.dialogMarketing.open({ hasCheckedIds }).then(res => {
        this.$refs.form.clearValidate(['biz.params.activityList'])
        this.form.biz.params.activityList = this.form.biz.params.activityList.concat(res)
      })
    }
    /**
     * 状态组
     */
    /**
     * 方法组
     */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.marketing-main {
  margin-top: 10px;
}

.w-400 {
  width: 400px;
}

/* 格式化 */
::v-deep {
  .el-card__body {
    padding: 10px;
  }

  .el-card__header {
    padding: 10px 20px;
  }
}

/*列表*/
.li-container {
  margin-top: 10px;
  cursor: move;

  .pic-box {
    margin-right: 10px;
    flex: 0 0 100px;
    height: 100px;
  }

  .content-box {
    flex: 1;
    margin-right: 10px;
    font-size: 14px;

    .cell-item {

      .label {
        flex: 0 0 80px;
        text-align: right;
      }
    }
  }

  .handle-box {
    // flex: 0 0 40px;
    text-align: right;
  }
}

</style>
